package com.leyou.user.web;

import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("info")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 校验数据是否存在
     * @param data 数据
     * @param type 类型
     * @return 布尔，true：存在，false：不存在
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> infoExists(@PathVariable("data")String data, @PathVariable("type") Integer type){
        return ResponseEntity.ok(userService.infoExists(data, type));
    }

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @return 无
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone){
        userService.sendVerifyCode(phone);
        // 返回204
        return ResponseEntity.noContent().build();
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @param code 验证码
     * @return 无
     */
    @PostMapping
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        // 不管@Valid校验结果如何，都会进入这里，我们要手动判断是否校验通过
        if(result.hasErrors()){
            String msg = result.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage).collect(Collectors.joining("|"));
            throw new LyException(400, msg + "滚，再捣乱我就报警了！");
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户
     * @param username 用户名
     * @param password 密码
     * @return 用户信息
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username, @RequestParam("password") String password
    ){
        return ResponseEntity.ok(userService.queryUserByUsernameAndPassword(username, password));
    }

}
